var api = require('../../utils/api.js');
var app = getApp();
Page({
  data: {
    imgUrls: [],
    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    swiperCurrent:0,
    phone:'4000-888-980',
    select_tabs_key: 5,
    select_tabs_0_value:'',
    select_tabs_1_value: '',
    select_tabs_2_value: '',
    select_tabs_3_value: '',
    filter_id0: 0,
    filter_id1: 0,
    filter_id2: 0,
    filter_value0: '',
    filter_value1: '',
    filter_value2: '',
    systemInfo: {},
    _api: {},
    list: [],
    total: 0,
    loadingMore: false,
    noMoreData: false,
    search_text_length: 0,
    searchInputShowed: false,
    searchInputVal: "",
    searchingResult: false,
    searchKeyword: "",
    pwd: '',//视频密码
    has_pwd: false,// false没有密码 true有密码
    verify_pwd: false,//判断输入密码是否正确
    focus: true,
    grades:[],//全部年级
    subjects:[],//全部科目
    recommend:[],//推荐
    logo:[],
    keyword:[],
  },
  currentPageNumber: 1,

  // 获取收拾框输入的文本内容
  search_txt(e) {
    this.setData({
      keyword: e.detail.value,
      search_text_length: e.detail.value.length
    })
  },


  // 轮播图切换图标
  swiperChange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },

  // 拨打电话
  call_phone:function(e){
    wx.makePhoneCall({
      phoneNumber: this.data.phone
    })
  },


  /**
   * 搜索微课堂
   * code=1 有查到相关数据
   * code=0 暂无相关数据
   */
  searchLesson(e) {
    let keyword = this.data.keyword
    console.log(keyword)
    api.post({
      url: 'wxapp/Index/searchLesson',
      data: {
        keyword: keyword
      },
      success: data => {
        if (data.code == 1) {
          this.setData({
            list: data.data
          });
        } else if (data.code == 0) {
          wx.showToast({
            title: data.msg,
            image: '/images/icons/fail2.png',
            duration: 2000
          })
          return false;
        }
      }
    })
  },

  // 筛选切换1
  select_menu_0: function (e) {
    console.log(0)
    if (this.data.select_tabs_key == e.currentTarget.dataset.id) {
      this.setData({
        select_tabs_key: 5
      })
    } else {
      this.setData({
        select_tabs_key: e.currentTarget.dataset.id
      })
    }
  },
  // 筛选切换2
  select_menu_1: function (e) {
    this.setData({
      select_tabs_key: e.currentTarget.dataset.id
    })
  },
  // 筛选切换3
  select_menu_2: function (e) {
    this.setData({
      select_tabs_2_value: !this.data.select_tabs_2_value
    })
  },
  // 筛选切换4
  select_menu_3: function (e) {
    if (this.data.select_tabs_key == e.currentTarget.dataset.id) {
      this.setData({
        select_tabs_key: 5
      })
    } else {
      this.setData({
        select_tabs_key: e.currentTarget.dataset.id
      })
    }
  },

  // 第一个筛选事件
  select_tabs_0:function(e){
    this.setData({
      select_tabs_0_value: e.currentTarget.dataset.id,
    })

    //搜索课程
    this.searchLessons(this.data.select_tabs_key, e.currentTarget.dataset.id);
    this.setData({
      select_tabs_key: 5
    })
  },
  // 第二个筛选事件
  select_tabs_1: function (e) {
    this.setData({
      select_tabs_1_value: e.currentTarget.dataset.id
    })

    //搜索课程
    this.searchLessons(this.data.select_tabs_key, e.currentTarget.dataset.id);
  },
  // 第三个筛选事件
  select_tabs_2: function (e) {
    this.setData({
      select_tabs_2_value: e.currentTarget.dataset.id
    })

    //搜索课程
    this.searchLessons(this.data.select_tabs_key, e.currentTarget.dataset.id);
  },
  // 第四个筛选事件
  select_tabs_3: function (e) {
    this.setData({
      select_tabs_3_value: e.currentTarget.dataset.id
    })
  },

  // 年级 科目 上传时间筛选
  filter: function (e) {

    console.log(e);
    let tp = e.currentTarget.dataset.type;
    let id = e.currentTarget.dataset.id;
    let tit = e.currentTarget.dataset.tit;
    let key = "filter_value" + tp;
    let keyid = "filter_id" + tp;
    console.log(tp);
    if (tp == 0) {
      this.setData({
        filter_value0: tit,
        filter_id0: id,
      })
    } else if (tp == 1) {
      this.setData({
        filter_value1: tit,
        filter_id1: id,
      })
    } else if (tp == 2) {
      this.setData({
        filter_value2: tit,
        filter_id2: id,
      }) 
    } else{
    
     console.log(tp);

    
     //根据选择年级、科目、上传时间筛选课程
     api.post({
       url: 'wxapp/Index/postChooseLessons',
       data: {
         grade_id: id,
         subject_id: '',
         time_id: '',
       },
       success: res => {
         this.setData({
           select_tabs_key: 5,
           list: res.data
         });
       }
     })
    }
  },

  // 年级 科目 上传时间重置
  filter_reset: function () {
    this.setData({
      filter_id0: 0,
      filter_id1: 0,
      filter_id2: 0,
      filter_value0: '',
      filter_value1: '',
      filter_value2: '',
    })
  },
  // 年级 科目 上传时间确定
  filter_ok: function () {
    let that = this.data;
    console.log(that.filter_id0)
    console.log(that.filter_id1)
    console.log(that.filter_id2)
    console.log(that.filter_value0)
    console.log(that.filter_value1)
    console.log(that.filter_value2)

    let grade_id = that.filter_id0;
    let subject_id = that.filter_id1;
    let time_id = that.filter_id2;

    //根据选择年级、科目、上传时间筛选课程
    api.post({
      url:'wxapp/Index/postChooseLessons',
      data:{
        grade_id: grade_id,
        subject_id: subject_id,
        time_id: time_id
      },
      success: res => {
        this.setData({
          select_tabs_key: 5,
          list: res.data
        });
      }
    })
  },

  //条件筛选
  searchLessons(sort, condition){
    // console.log('排序:' + sort)
    // console.log('条件:' + condition)
    api.post({
      url:'wxapp/Index/searchLessons',
      data:{
        sort: sort,
        condition: condition
      },
      success:res =>{
        console.log(res.data)
        this.setData({
          list: res.data
        });
      }
    })
  },
  onUnload(){
    this.setData({
      has_pwd: true,
      focus: true,
    });
  },
  onLoad() {
    api.get({
      url: 'wxapp/product/getLogo',
      data: {
      },
      success: data => {
        this.setData({
          logo: data.data
        });
      }
    });
    try {
      var isLogin = wx.getStorageSync('login');
      if (!isLogin) {
        api.login();
        return;
      }
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      _api: api,
    });

    api.get({
      url: 'wxapp/product/getRecommend',
      data: {},
      success: res => {
        // console.log(JSON.stringify(res.data));
        this.setData({
         recommend:res.data
        })
      }
    })
   

  },

  onReady() {
    this.loadData();
  },

  loadData(){
    api.get({
      url: 'wxapp/Index/wx_index',
      data: {
        page: this.currentPageNumber,
        order: '-published_time'
      },
      success: data => {
        let newItems = api.updatePageList('id', data.data, this.formatListItem);
        console.log(newItems);
        this.setData({
          list: newItems
        });
        if (data.data.length > 0) {
          this.currentPageNumber++;
        } else {
          this.setData({
            noMoreData: true
          });
        }
      },
      complete: () => {
        this.setData({
          loadingMore: false
        });
        wx.hideNavigationBarLoading();
      }
    });
  },

  onShow() {
    console.log(app.pagesNeedUpdate);
    if (app.pagesNeedUpdate['pages/index/index'] == 1) {
      let newItems = api.updatePageList('id');
      console.log(newItems);
      this.setData({
        list: newItems
      });
    }

    if (app.pagesNeedUpdate['pages/index/index'] == 'refresh') {
      this.onPullDownRefresh();
    }
    this.pullUpLoad();

    api.pageNeedUpdate('pages/index/index', 0);
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.currentPageNumber = 1;
    this.setData({
      noMoreData: false,
      noData: false
    });
    api.get({
      url: 'wxapp/Index/wx_index',
      data: {
        order: '-published_time'
      },
      success: data => {
        let newItems = api.updatePageList('id', data.data, this.formatListItem, true);
        console.log(newItems);
        this.setData({
          list: newItems
        });

        if (data.data.length > 0) {
          this.currentPageNumber++;
        } else {
          this.setData({
            noMoreData: true
          });
        }

        wx.stopPullDownRefresh();
      }
    });
  },

  /**
   * 上拉刷新
   */
  pullUpLoad() {
    if (this.data.loadingMore || this.data.noMoreData) return;
    var user = wx.getStorageSync('user');//用户信息
    this.setData({
      user_id: user.id,
      loadingMore: true
    });
    // wx.showNavigationBarLoading();
    //获取课程列表
    // api.get({
    //   url: 'wxapp/Index/wx_index',
    //   data: {
    //     page: this.currentPageNumber,
    //     order: '-published_time'
    //   },
    //   success: data => {
    //     let newItems = api.updatePageList('id', data.data, this.formatListItem);
    //     console.log(newItems);
    //     this.setData({
    //       list: newItems
    //     });
    //     if (data.data.length > 0) {
    //       this.currentPageNumber++;
    //     } else {
    //       this.setData({
    //         noMoreData: true
    //       });
    //     }
    //   },
    //   complete: () => {
    //     this.setData({
    //       loadingMore: false
    //     });
    //     wx.hideNavigationBarLoading();
    //   }
    // });

    //获取全部年级和全部科目
    api.get({
      url:'wxapp/Index/listGradeSubject',
      data:{},
      success:res => {
        this.setData({
          grades: res.grades,
          subjects: res.subjects
        })
      }
    }),

    //获取广告信息
      api.get({
        url: 'wxapp/Index/Ad',
        data: {
          id:3
        },
        success: res => {
          this.setData({
            imgUrls: res
          })
        }
      })  
  },

  formatListItem(item) {
    if (item.Thumbnail) {
      item.Thumbnail = api.getUploadUrl(item.Thumbnail);
    }
    return item;
  },

  onReachBottom() {
    this.pullUpLoad();
  },

  //跳转点击的课程页面
  onListItemTap(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/article/article?id=' + id
    });
    //判断该课程是否有密码
    // api.post({
    //   url: 'wxapp/Index/isset_pwd',
    //   data:{
    //     id: id
    //   },
    //   success:res=>{
    //     if(res.data.post_pwd){
    //       this.setData({
    //         art_id: id,
    //         pwd: res.data.post_pwd,
    //         has_pwd:true
    //       })
    //     }else{
    //       wx.navigateTo({
    //         url: '/pages/article/article?id=' + id
    //       });
    //     }
    //   }
    // })
  },

  showSearchInput() {
    this.setData({
      searchInputShowed: true,
      searchingResult: false
    });
  },
  hideSearchInput() {
    this.setData({
      searchInputVal: "",
      searchKeyword: "",
      searchInputShowed: false,
      searchingResult: false
    });
    this.onPullDownRefresh();
  },
  clearSearchInput() {
    this.setData({
      searchInputVal: "",
      searchKeyword: "",
      searchingResult: false
    });
    this.onPullDownRefresh();
  },
  searchInputTyping(e) {
    this.setData({
      searchInputVal: e.detail.value,
      searchKeyword: "",
      searchingResult: false
    });
  },
  searchSubmit() {
    this.setData({
      searchingResult: true,
      searchKeyword: this.data.searchInputVal
    });
    this.onPullDownRefresh();
  },
  previewImage(e) {
    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.previewUrl] // 需要预览的图片http链接列表
    });

  },


  //分享
  onShareAppMessage(e) {
    let user_id = this.data.user_id
    return {
      path: '/pages/index/index',
      success: function (res) {
        api.post({
          url: 'wxapp/Index/share',
          data: {
            title: '微课',
            user_id: user_id
          },
          success: res => {
            wx.showToast({
              title: res.msg,
              icon: 'success',
              duration: 2000
            })
          }
        })
      },
    }
  },

  //弹出框的取消按钮
  onCancel: function () {
    this.setData({
      has_pwd: false,
      focus: false,
    });
  },

  //弹出框的确定按钮
  onConfirm(){
    var that = this;

    if (this.data.pwd_input == this.data.pwd){
      this.setData({
        has_pwd: false,
        focus: false,
      });
      wx.navigateTo({
        url: '/pages/article/article?id=' + this.data.art_id
      });
    }else{
      wx.showModal({
        title: '提示',
        content: '密码错误',
        showCancel: false,
        success: function (res) {
          console.log(res)
          if (res.confirm) {
            that.setData({
              has_pwd: true,
              focus: true
            })
          }
        }
      })
      return
    }
  },

  //弹出框的输入框
  priceInput(e){
    this.setData({
      pwd_input: e.detail.value
    })
  },


  goNewPage(e) {
    let go_url = e.currentTarget.dataset.url

    if (go_url > 0) {
      wx.navigateTo({
        url: '/pages/public/public?url=' + go_url
      })
    }
  }
});


